package org.njbdqn.ali.database;

import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class SqlTemplate {
	private DbManager dbm;
	
	public int update(String sql, Object [] params) {
		dbm = new DbManager();
		int count = 0;
		try {
			count = dbm.update(sql, params);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			dbm.destroy();
		}
		return count;
	}
	
	public <T>List<T> resultToArray(String sql, Object[] params, Class cls){
		dbm = new DbManager();
		List<T> list = new ArrayList<T>();
		ResultSet rs = dbm.query(sql, params);
		Field [] fields = cls.getDeclaredFields();
		try {
			while(rs.next()) {
				Object obj = cls.newInstance();
				for(Field f:fields) {
					f.setAccessible(true);
					try {
						f.set(obj, rs.getObject(f.getName()));
					}catch(Exception e) {
						continue;
					}
				}
				list.add((T)obj);
			}
		} catch (InstantiationException e) {
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbm.destroy();
		}
		return list;
	}
	
	public Object resultToObject(String sql,Object [] params) {
		dbm = new DbManager();
		Object obj = null;
		ResultSet rs = dbm.query(sql, params);
		try {
			if(rs.next()) {
				obj = rs.getObject(1);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			dbm.destroy();
		}
		return obj;
	}
}
